// 云函数入口文件
const cloud = require('wx-server-sdk')
const ResponseDTO = require('./res');
const {Validator}  = require('./tool/index')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

// 定义数据库 -- 统一使用单数形式
const USER = 'cloud_wx_user';

// 数据库引入
const db = cloud.database();

// 云函数入口函数
exports.main = async (event, context) => {
  switch(event.action){
    case 'putUserProfile':{
      return putUserProfile(event,context)
    }
    case 'getUserProfile':{
      return getUserProfile(event,context)
    }
  }
}
// 用户基础信息相关操作
async function getUserProfile(event,context){
  const wxContext = cloud.getWXContext()
  let openId = wxContext.OPENID
  try {
    let res = await db.collection(USER).doc(openId).get();
    return ResponseDTO.succData(res.data);
  } catch (error) {
    return ResponseDTO.wrap(404,"用户信息不存在");
  }
}

async function getUserInfo(event,context){
  return getUserProfile(event,context)
}

async function putUserProfile(event,context){
  const wxContext = cloud.getWXContext()
  let openId = wxContext.OPENID
  let data = event.data
  try {
    let res = await db.collection(USER).doc(openId).set({
      data
    })
    console.log(res)
    return ResponseDTO.succData(data)
  } catch (error) {
    return ResponseDTO.wrap(500,"数据更新异常")
  }
}

async function putUserInfo(event,context){
  return putUserProfile(event,context)
}